﻿using System;
using System.Collections.Generic;
using System.Text;
using ElteIk.RoboSoccer.Core;
using ElteIk.RoboSoccer.Communication;
using ElteIk.RoboSoccer.Core.Physics;

namespace ElteIk.RoboSoccer.TesterTactics
{
    /// <summary>
    /// Random tactics means - Move to random targets, sometime the ball is the target.
    /// </summary>
    public class RandomTactics : ITactics
    {
        #region Private fields

        protected RoboSoccerGame game;
        protected RoboSoccerTeam team;

        protected SimpleController[] robotControllers;

        protected int teamId;

        protected Vector2D[] targets;
        protected decimal targetsSettedTime;
        protected decimal targetsTimeOut;

        #endregion

        #region Lifecycle

        public RandomTactics(int teamId)
        {
            this.teamId = teamId;
        }

        public void InitializeTactics(RoboSoccerGame game, int teamId)
        {
            this.game = game;

            if (teamId == 1)
                this.team = game.LeftTeam;
            else if (teamId == 2)
                this.team = game.RightTeam;

            // Setup robotContollers
            robotControllers = new SimpleController[team.Players.Count];
            for (int i = 0; i < team.Players.Count; ++i)
                robotControllers[i] = new SimpleController(team.Robots[i], game.Field);

            // Setup targets
            targets = new Vector2D[team.Players.Count];
            for (int i = 0; i < team.Players.Count; ++i)
                targets[i] = new Vector2D(game.Ball.Position);

            targetsSettedTime = game.Time;
            targetsTimeOut = 2.0m;
        }

        #endregion

        #region Public properties

        public RoboSoccerGame Game
        {
            get { return game; }
            set
            {
                game = value;
                InitializeTactics(game, teamId);
            }
        }

        #endregion

        #region Tactics

        public void Do()
        {
            if (game == null)
                return;

            // Random target choes
            Random r = new Random();
            if (game.Time - targetsSettedTime >= targetsTimeOut)
            {
                if (r.NextDouble() > 0.2)
                    targets[r.Next(0, 2)] = new Vector2D(game.Ball.Position);
                else
                    targets[r.Next(0, 2)] = new Vector2D(r.Next(40,150),r.Next(40,130));

                targetsSettedTime = game.Time;
                targetsTimeOut = Convert.ToDecimal(r.NextDouble() * 4.0);
            }

            for(int i = 0; i < team.Players.Count; i++)
                robotControllers[i].MoveTo(targets[i]);
        }

        #endregion
    }
}
